package com.richapp.launcher.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.OutputStream;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.List;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.PowerManager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.jack.util.string.StringUtil;
import com.richapp.launcher.R;
import com.richapp.launcher.database.infrared.dao.ButtonDao;
import com.richapp.launcher.database.infrared.dao.MachineTypeDao;
import com.richapp.launcher.database.infrared.mode.Button;
import com.richapp.launcher.database.infrared.mode.MachineType;

public class Tools {

    private static final String TAG = Tools.class.getName();
    public static String cpuAddress = "0000000000000000";
    public static int UPDATE_COUNT = 0;
    public static  String clientId="";

    /**
     * 获取CPU序列号
     *
     * @return CPU序列号(16位) 读取失败为"0000000000000000"
     */
    public static String getCPUSerial() {
        if (cpuAddress == null || "0000000000000000".equals(cpuAddress)) {
            String str = null;
            String strCPU = null;
            try {
                // 读取CPU信息
                Process pp = Runtime.getRuntime().exec("cat /proc/cpuinfo");
                InputStreamReader ir = new InputStreamReader(pp.getInputStream());
                LineNumberReader input = new LineNumberReader(ir);
                // 查找CPU序列号
                for (int i = 1; i < 100; i++) {
                    str = input.readLine();
                    if (str != null) {
                        // 查找到序列号所在行
                        if (str.indexOf("Serial") > -1) {
                            // 提取序列号
                            strCPU = str.substring(str.indexOf(":") + 1, str.length());
                            // 去空格
                            cpuAddress = strCPU.trim();
                            break;
                        }
                    } else {
                        // 文件结尾
                        break;
                    }
                }
                ir.close();
                input.close();
                //pp.destroy();
            } catch (Exception ex) {
                // 赋予默认值
            }
        }
        return cpuAddress;
    }


    /**
     * 获取经销商序列号
     *
     * @return CPU序列号(8位)
     */
    public static String getDistributorSerial() {
            String strDistributorId= null;
            try {
                // 读取CPU信息
                IniUtil iniUtil = new IniUtil("system/etc/client_id.ini");
                strDistributorId= iniUtil.get("general","clientid").get(0);
            } catch (Exception ex) {
                // 赋予默认值
            }

        return strDistributorId;
    }


    /**
     * @param side 表示要查询的是内网地址还是外网地址
     *             0 查询内网地址
     *             1 查询外网地址
     *             2 查询所有地址
     * @return 所有可用的IP地址集合
     */
    public static List<String> getAllIps(int side) {
        List<String> ipList = new LinkedList<String>();
        try {
            Enumeration<NetworkInterface> networkInterfaceList = NetworkInterface.getNetworkInterfaces();
            NetworkInterface networkInterface = null;
            InetAddress inetAddress = null;
            Enumeration<InetAddress> inetAddressList = null;

            while (networkInterfaceList.hasMoreElements()) {
                networkInterface = networkInterfaceList.nextElement();
                inetAddressList = networkInterface.getInetAddresses();
                while (inetAddressList.hasMoreElements()) {
                    inetAddress = inetAddressList.nextElement();
                    if (inetAddress != null
                            && inetAddress instanceof Inet4Address
                            && !inetAddress.isLoopbackAddress()) {
                        switch (side) {
                            case 0:
                                if (inetAddress.isSiteLocalAddress()) {
                                    ipList.add(inetAddress.getHostAddress());
                                }
                                break;
                            case 1:
                                if (!inetAddress.isSiteLocalAddress()) {
                                    ipList.add(inetAddress.getHostAddress());
                                }
                                break;
                            case 2:
                                ipList.add(inetAddress.getHostAddress());
                                break;
                            default:
                                break;
                        }
                    }
                }
            }
        } catch (Exception e) {
            Log.v("error", "获取IP错误:" + e.getMessage());
        }
        return ipList;
    }

    /**
     * 导入红外码库数据
     */
    public static void importDatabaseRawFile(Context context) {
        try {
            InputStream inputStream = context.getResources().openRawResource(R.raw.infrared);

            String databaseName = "/data/data/" + context.getPackageName() + "/databases/infrared.db";
            File dest = new File(databaseName);
            if(UPDATE_COUNT != 0){
                return;
            }

            if(dest.exists()){
                ButtonDao buttonDao = new ButtonDao(context);
                List<Button> buttons = buttonDao.getButtonTemplete(5);
                if(buttons == null || buttons.size() < 1){
                    dest.delete();
                }else{
                    return;
                }
            }

            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            OutputStream outputStream = new FileOutputStream(dest);
            byte[] buffer = new byte[1024];
            int length = -1;
            while ((length = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, length);
            }
            inputStream.close();
            outputStream.close();
            Log.d(TAG, "导入红外码库成功!");

            UPDATE_COUNT++;
            Log.d(TAG, "码库已是最新版本!");
        } catch (Exception e) {
            Log.e(TAG, "导入红外码库数据出错!");
        }
    }

    public static void openDefaultBrowser(Context context){
        try{
            /*Intent intent = new Intent();
            intent.setAction("android.intent.action.VIEW");
            Uri content_url = Uri.parse("http://i.ufosmart.com:8081/ufosmart/toLogin");
            intent.setData(content_url);
            intent.setClassName("com.android.browser","com.android.browser.BrowserActivity");
            context.startActivity(intent);*/
            openApp(context,"com.android.browser");
        }catch (Exception e){
            Log.e(Tools.class.getName(),"打开浏览器错误:"+e.getMessage());
        }
    }

    /**
     * 检测服务是否启动
     *
     * @param context
     * @param serviceClassName
     * @return
     */
    public static boolean isServiceRun(Context context, String serviceClassName) {
        boolean flag = false;
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> serviceInfoList = activityManager.getRunningServices(30);
        if (serviceInfoList.size() > 0) {
            for (ActivityManager.RunningServiceInfo ar : serviceInfoList) {
                if (ar.service.getClassName().equals(serviceClassName)) {
                    flag = true;
                    break;
                }
            }
        }
        return flag;
    }


    public static void restartSystem(Context context) {
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        pm.reboot("系统自我维护重启");
    }

    public static void restartSystem(Context context, String content) {
        if (StringUtil.isNullOrEmpty(content)) {
            content = "系统自我维护重启";
        }

        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        pm.reboot(content);
    }

    public static void openApp(Context context, String packageName) {
        if (ApkUtil.isExistApp(context, packageName)) {
            try {
                Intent intent = context.getPackageManager().getLaunchIntentForPackage(packageName);
                context.startActivity(intent);
            } catch (Exception e) {
                Toast.makeText(context, "打开失败!" + e.getMessage(), Toast.LENGTH_SHORT).show();
                Log.e(TAG, e.getMessage());
            }
        } else {
            Toast.makeText(context, "没有安装!", Toast.LENGTH_SHORT).show();
        }
    }

    public static void toastTip(Context context, int drawableId) {
        Toast toast = new Toast(context);
        LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = layoutInflater.inflate(R.layout.toast_tip, null);
        ImageView imageView = (ImageView) view.findViewById(R.id.imageViewShow);
        imageView.setBackgroundResource(drawableId);
        toast.setView(view);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }

    public static String getStringValue(String str) {
        if (str == null) {
            return "";
        } else {
            return str.trim();
        }
    }

    public static boolean isAPKRun(Context context, String packageName) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.processName.equals(packageName)) {
                return true;
            }
        }
        return false;
    }

    public static boolean isAPKBackground(Context context) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.processName.equals(context.getPackageName())) {
                if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND) {
                    Log.i("后台", appProcess.processName);
                    return true;
                } else {
                    Log.i("前台", appProcess.processName);
                    return false;
                }
            }
        }
        return false;
    }

    /**
     * Dean
     * ping 外网地址判断网络是否可用
     * @return
     */
    public static final boolean ping() {

        String result = null;
        try {
            String ip = "39.108.55.223";// ping 的地址，可以换成任何一种可靠的外网
            Process p = Runtime.getRuntime().exec("ping -c 2 -w 15 " + ip);// ping网址3次超时时间10秒
            // 读取ping的内容，可以不加
            InputStream input = p.getInputStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(input));
            StringBuffer stringBuffer = new StringBuffer();
            String content = "";
            while ((content = in.readLine()) != null) {
                stringBuffer.append(content);
            }
            Log.d("------ping-----", "result content : " + stringBuffer.toString());
            // ping的状态
            int status = p.waitFor();
            if (status == 0) {
                result = "success";
                return true;
            } else {
                result = "failed";
                return false;
            }
        } catch (IOException e) {
            result = "IOException";
        } catch (InterruptedException e) {
            result = "InterruptedException";
        } finally {
            Log.d("----result---", "result = " + result);
        }
        return false;
    }
}
